/*
 This file is part of BTStracker
		
    BTStracker is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    BTStracker is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Foobar.  If not, see <http://www.gnu.org/licenses/>.	
	author: azbest.pro (azbest.pro@gmail.com)
*/
package pl.vdl.azbest.mremote.probe.signal;

import java.io.IOException;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Formatter;
import java.util.LinkedList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Logger;

import pl.vdl.azbest.log.LoggingTheGathering;
import pl.vdl.azbest.mremote.Conf;
import pl.vdl.azbest.mremote.cmd.Cmd_getBTSCellName;
import pl.vdl.azbest.mremote.cmd.Cmd_sendCommCommand;
import pl.vdl.azbest.mremote.cmd.Command;
import pl.vdl.azbest.mremote.cmd.Invoker;
import pl.vdl.azbest.mremote.com.CConnect;
import pl.vdl.azbest.mremote.com.TextOutputStream;
import pl.vdl.azbest.mremote.gui.GUIFacade;
import pl.vdl.azbest.mremote.gui.composite.CompositeCellSignalTable;
import pl.vdl.azbest.mremote.mob.ATAnwser;
import pl.vdl.azbest.mremote.mob.ATObserver;
import pl.vdl.azbest.mremote.mob.ATOutputStream;
import static pl.vdl.azbest.mremote.mob.ATAnwser.*;

public class CellSignalProbe implements ATObserver {
	private int n = Conf.getInstance().getGPRSCellQueringCount();
	private static CellSignalProbe instance = new CellSignalProbe();
	

	private LinkedList<String> llist = new LinkedList<String>();

	private Logger logger = Logger.getLogger(getClass().getName());
	{
		LoggingTheGathering.addPath(getClass().getName());
		ATOutputStream.getInstance().addObservers(this);
	}
	public static CellSignalProbe getInstance() {
		if (instance != null) {
			return instance;
		} else {
			synchronized (GUIFacade.class) {
				instance = new CellSignalProbe();
				return instance;
			}
		}
	}
	private CellSignalProbe ( ){}

	public void doCheck() {
		// got COM stem reader
		// Now writing commands to comm
		// Command c = new Cmd_getBTSCellName();
		// Invoker.getInstance().addCommand(c);
		// Invoker.getInstance().execute();
		// receive data
		// String s = CConnect.getInstance().getMRStream().getAnwser();
		// add notify here .
		// //System.out.println(">"+s);
		// Set phone to
		logger.info("Set phone (k300i) to BTS GPRS cell report mode");
		Command c = new Cmd_sendCommCommand("AT+CGREG=2");
		Invoker.getInstance().addRunnableCommand(c);

		logger.info("Start quering in "
				+ Conf.getInstance().getGPRSCellQueringRateSeconds()
				+ " seconds");
		// Conf.getInstance().getGPRSCellQueringRateSeconds()

		final int interval = Conf.getInstance().getGPRSCellQueringRateSeconds() * 1000;
		final Timer timer = new Timer();
		class MyTimerTask extends TimerTask {
			public void run() {
				logger
						.info("What is your BTS GPRS cell and sector  name ? What is your signal level ?");
				Command c2 = new Cmd_sendCommCommand("AT+CGREG?");
				Invoker.getInstance().addRunnableCommand(c2);

				Command c3 = new Cmd_sendCommCommand("AT+CSQ");
				Invoker.getInstance().addRunnableCommand(c3);

				n--;

				// timer.cancel();
				if (n > 0) {
					timer.schedule(new MyTimerTask(), interval);
				} else {
					timer.cancel();
				}
			}
		}// MyTimerTask
		timer.schedule(new MyTimerTask(), interval);
	}

	CellSignalData csd = new CellSignalData();

	public void update(ATAnwser at) {
		if (csd == null)
			csd = new CellSignalData();

		Date date = new Date();

		if (csd.getTime() != null)
			csd.setTime(date.toString());

		switch (at) {
		case CGREG:
			csd.setCI((String) at.getData().get(1));
			csd.setLAI((String) at.getData().get(0));
			break;
		case CSQ:
			csd.setSignal(at.getData().get(0));
			break;

		default:
			// do nothing
			break;
		}
		printCSD(csd);
		if (csd.isFull()) {
			printCSD(csd);
			TextOutputStream tos = GUIFacade.getInstance()
					.getTextOutputStream();
			String s = csd.toString();
			char[] ach = s.toCharArray();
			for (int i : ach) {
				try {
					tos.write(i);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			// GUIFacade.getInstance().
			notifyObservers();

			csd = null;
		}
	}

	private void printCSD(CellSignalData csd) {
		System.out.println(csd.toString());
	}

	private void parseATCommand(ATAnwser at) {

		/*
		 * AT+CGREG?
		 * 
		 * +CGREG: 2,5,"0F2B","0000557B"
		 * 
		 * OK
		 * 
		 */

		/*
		 * AT+CSQ
		 * 
		 * +CSQ: 18,99
		 * 
		 * OK
		 * 
		 */

		/*
		 * 
		 */

	}

	private List<CellSignalProbeObserver> list = 
		new ArrayList<CellSignalProbeObserver>();

	public void addObservers(CellSignalProbeObserver observer) {
		list.add(observer);
	}

	public void removeObservers(CellSignalProbeObserver observer) {
		list.remove(observer);
	}

	public void notifyObservers() {
		if(csd == null) return;
		for(CellSignalProbeObserver o: list){
			o.update(csd);
		}
	}

}
